package tools.vetorial;

import java.awt.Color;

import core.Clip;
import core.DrawContext;
import core.Object2D;
import core.OurGraphics;
import core.Point3D;
import core.VectorialObject;

public class VectorialClippingTool extends PointSelectionTool {

	private VectorialRectProxy mProxy = new VectorialRectProxy();
	
	private Point3D mProxyPt2 = new Point3D(0, 0);
	
	private Point3D mProxyPt1 = new Point3D(0, 0);
	
	private boolean mPoint1Selected = false;

	@Override
	public Object2D getProxy() {
		return mProxy;
	}

	@Override
	public void pencilDown(DrawContext ctx) {
	}

	@Override
	public void pencilUp(DrawContext ctx) {
		if(mPoint1Selected) {
			Clip clip = new Clip(mProxyPt1, mProxyPt2);
			clip(clip, ctx);
			mPoint1Selected = false;
		}
	}

	@Override
	public void updateProxy(int x, int y, DrawContext ctx) {
		mProxyPt2.setX(x);
		mProxyPt2.setY(y);
	}
	
	private void clip(Clip c, DrawContext ctx) {
		
		int xMin = c.getPoint1().getX();
		int xMax = c.getPoint2().getX();
		int yMin = c.getPoint1().getY();
		int yMax = c.getPoint2().getY();
		
		if(xMax < xMin) {
			xMin = c.getPoint2().getX();
			xMax = c.getPoint1().getX();
		}
		
		if(yMax < yMin) {
			yMin = c.getPoint2().getY();
			yMax = c.getPoint1().getY();
		}
		
		for(Object2D obj : ctx.getObjects()) {
			if(obj instanceof VectorialObject) {
				((VectorialObject)obj).clipping(xMin, yMin, xMax, yMax);
			}
		}
		
		ctx.setChanged(true);
	}
	
	private class VectorialRectProxy implements Object2D {
		
		@Override
		public void draw(OurGraphics g2) {		
			
			if(!mPoint1Selected) {
				return;
			}
			
			g2.setColor(Color.BLUE);
			g2.setLinePattern(5);
			
			g2.drawSquare(mProxyPt1, mProxyPt2);
		}
		
	}

	@Override
	public void onSelection(VectorialObject vo) {
		// TODO Auto-generated method stub
	}

	@Override
	public void addPoint(int x, int y, int order, DrawContext ctx) {
		if(order%2 == 0) {
			mProxyPt1.setX(x);
			mProxyPt1.setY(y);
			mPoint1Selected = true;
		}else{
			mProxyPt2.setX(x);
			mProxyPt2.setY(y);
			pencilUp(ctx);
			pencilDown(ctx);
		}
	}

}
